package com.zcaxer.way.data

import android.content.Context
import androidx.annotation.WorkerThread
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

class BuildingRepository(context: Context) {

    val db = AppDatabase.getDatabase(context)
    private val buildingDao = db.buildingDao()
    private val buildingUpgradeInfoDao = db.buildingUpgradeInfoDao()
    val buildings = buildingDao.getBuildings()
    val producers = buildingDao.getProducers()
    val upgradeInfos: MutableList<List<Binomial>> = mutableListOf()

    init {
        runBlocking {
            launch {
                getAllUpgradeInfo()
            }
        }
    }

    fun getProducer()=buildingDao.getProducers()

    @WorkerThread
    suspend fun updateBuilding(building: Building) = buildingDao.updateBuilding(building)

    @WorkerThread
    suspend fun setReserve(reserve: Int, id: Int) = buildingDao.updateReserve(reserve, id)

    @WorkerThread
    suspend fun setWorkers(workers: Int, id: Int) = buildingDao.updateWorkers(workers, id)

    @WorkerThread
    suspend fun setTarget(target: Int, id: Int) = buildingDao.updateTarget(target, id)

    @WorkerThread
    suspend fun getUpgradeInfo(buildingId: Int) = buildingUpgradeInfoDao.query(buildingId)

    @WorkerThread
    suspend fun getAllUpgradeInfo(): List<List<Binomial>> {
        for (i in 0..7) {
            upgradeInfos.add(getUpgradeInfo(i))
        }
        return upgradeInfos
    }

    @WorkerThread
    suspend fun setWorkersNeed(workersNeed: Int, id: Int) = buildingDao.updateWorkersNeed(workersNeed, id)

    companion object {

        // For Singleton instantiation
        @Volatile
        private var instance: BuildingRepository? = null

        fun getInstance(context: Context) =
                instance ?: synchronized(this) {
                    instance ?: BuildingRepository(context).also { instance = it }
                }
    }


}